#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project : wupeiqi_async
@File : cocurrent.future.py
@Author : Royce
@Time : 2025/7/12 10:50
@脚本说明 :
"""

import time
import asyncio
import concurrent.futures
from util.util import timer


@timer('ms')
def func1(num):
    time.sleep(2)  # 某个耗时操作
    return num


@timer('ms')
async def main():
    '''普通的线程函数可以添加到事件循环,然后转换为协程函数'''
    loop = asyncio.get_running_loop()  # 获取得到当前的事件循环

    # # <editor-fold desc="1. 直接将普通的线程函数放入事件循环">
    # fut = loop.run_in_executor(None, func1)  # 将一个普通线程函数添加到事件循环并执行, 它将会被future对象追踪并管理
    #
    # result = await fut
    # print('default thread pool', result)
    # # </editor-fold>

    # <editor-fold desc="2. Run in a custom thread pool">
    with concurrent.futures.ThreadPoolExecutor() as thread_pool:
        result = await loop.run_in_executor(thread_pool, func1)  # 将异步的线程Future对象转换为异步的协程future对象(可以await)
    print('custom thread pool', result)
    # </editor-fold>

    # # <editor-fold desc="3. Run in a custom process pool">
    # with concurrent.futures.ProcessPoolExecutor() as pool:
    #     result = await loop.run_in_executor(pool, func1)  # 将异步的进程Future对象转换为异步的协程future对象(可以await)
    # print('custom process pool', result)
    # # </editor-fold>


if __name__ == '__main__':
    asyncio.run(main())
